﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using Common;
using BLL;
using System.Data;
using System.Data.SqlClient;

namespace WebPortal.Controllers
{
    public class SysMenuController : BaseController
    {
        SysMenuBLL m_BLL;

        public SysMenuController()
            : this(new SysMenuBLL()) { }

        public SysMenuController(SysMenuBLL bll)
        {
            m_BLL = bll;
        }
        /// <summary>
        /// 获取树形列表的数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllMetadata(string id, string keyword)
        {
            List<SysMenuInfo> rows = SysMenuBLL.GetInfoList();//获取树形列表的数据
            if (rows.Any())
            {
                return Json(new treegrid
                {
                    rows = rows.Select(s =>
                        new
                        {
                            Id = s.Id
                    ,
                            Name = s.Name
                    ,
                            _parentId = s.ParentId
                    ,
                            state = s.State
                    ,
                            Url = s.Url
                    ,
                            iconCls = s.Iconic
                    ,
                            Sort = s.Sort
                    ,
                            Remark = s.Remark
                    ,
                            CreatePerson = s.CreatePerson
                    ,
                            CreateTime = s.CreateTime
                    ,
                            UpdateTime = s.UpdateTime
                    ,
                            UpdatePerson = s.UpdatePerson

                        }
                        ).OrderBy(o => o.Sort)
                });
            }

            return Content("[]");
        }

        /// <summary>
        /// 获取树形页面的数据
        /// </summary>
        /// <returns></returns> 
        public ActionResult GetTree()
        {
            string userName = Request.Cookies["MDM_UserName"] == null ? "" : Request.Cookies["MDM_UserName"].Value;
            if (string.IsNullOrEmpty(userName))//登录超时
                return Json("");
            List<SystemTree> listTree = new List<SystemTree>();
            SystemTree sys = new SystemTree();
            var tree = new SysMenuTreeNodeCollection();

            string parentId = Request["parentid"];//父节点编号
            if (!string.IsNullOrEmpty(parentId))
            {
                SysPublicBLL pbll = new SysPublicBLL(new LoginInfo());
                DBDeploy dbp = pbll.GetDBInfo(parentId);
                if (dbp.DBStatus != 1)
                    return Json("");
            }
            DataTable dt = new DataTable();
            List<SysMenuInfo> trees = SysMenuBLL.GetInfoList();//获取树形页面的数据
            if (trees != null)
            {
                int i = 0;
                foreach (DBDeploy db in SysMenuBLL.GetDBList(""))
                {
                    int roletg = SysPublicBLL.GetUserEnableRole(userName, db.DBName);
                    if (roletg != 0)
                    {
                        List<SystemTree> listSystemTree = new List<SystemTree>();
                        if (db.DBStatus == 1)
                        {
                            if (string.IsNullOrEmpty(parentId))
                            {
                                tree.Bind(trees, null, ref listSystemTree, dt, db);
                            }
                            else if (db.DBName == parentId)
                            {
                                tree.Bind(trees, parentId, ref listSystemTree, dt, db);
                            }
                        }
                        if (sys.id == null && listSystemTree.Count > 0)
                            sys = listSystemTree.Find(o => { return o.text == "系统管理"; });
                        string iconCls = "icon-db";
                        if (db.DBType == 2)
                            iconCls = "icon-dbm";
                        if (db.DBStatus == 2)
                            iconCls = "icon-db_stop";
                        int dbConn = SysPublicBLL.GetUserDBConn(userName, db.DBName);
                        string treeID = roletg == 1 ? "-1" : db.DBStatus.ToString();
                        if (dbConn > 0)
                        {
                            iconCls = "icon-db_disLink";
                            treeID = "3";
                        }
                        List<SystemTree> children = new List<SystemTree>();
                        if (SysPublicBLL.GetUserRole(userName, db.DBName) > 0 && dbConn == 0)
                            children = listSystemTree.FindAll(o => { return o.text != "系统管理"; });
                        SystemTree addParent = new SystemTree()
                        {
                            text = db.DisplayName,
                            value = db.DBName,
                            id = treeID,
                            job = db.DBJobStatus.ToString(),
                            state = "closed",
                            iconCls = iconCls,
                            children = children
                        };
                        i++;
                        listTree.Add(addParent);
                    }
                }
            }
            RoleBll roleBll = new RoleBll(new LoginInfo());

            if (sys != null && roleBll.GetUserByRoleName("系统管理员", userName))
            {
                sys.children.ForEach(o => { o.attributes.url = o.attributes.url.Substring(0, o.attributes.url.IndexOf("?")); });
                listTree.Add(sys);
            }
            JsonResult jr = Json(listTree, JsonRequestBehavior.AllowGet);
            return jr;
        }
        public ActionResult DBList()
        {
            string dbType = Request.Params["dbType"];
            return Json(SysMenuBLL.GetDBList(dbType));
        }
        public ActionResult GetDBListInnerJob()
        { 
            return Json(new SysMenuBLL().GetDBListInnerJob());
        }
        #region 菜单方法
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        ///[SupportFilter]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Index1()
        {
            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<SysMenuInfo> queryData = null; //m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    Id = s.Id
                    ,
                    Name = s.Name
                    ,
                    ParentId = s.ParentId
                    ,
                    Url = s.Url
                    ,
                    Iconic = s.Iconic
                    ,
                    Sort = s.Sort
                    ,
                    Remark = s.Remark
                    ,
                    State = s.State
                    ,
                    CreatePerson = s.CreatePerson
                    ,
                    CreateTime = s.CreateTime
                    ,
                    UpdateTime = s.UpdateTime
                    ,
                    UpdatePerson = s.UpdatePerson

                }

                    )
            });
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Details(string id)
        {
            SysMenuInfo item = SysMenuBLL.GetInfoById(id);
            return View(item);

        }

        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        //[SupportFilter]
        public ActionResult Create(string id)
        {

            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(SysMenuInfo entity)
        {
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = "superadmin";
                entity.CreateTime = DateTime.Now;
                entity.CreatePerson = currentPerson;
                entity.Id = StringHelper.GetNewId();
                string returnValue = string.Empty;
                m_BLL.Insert(entity);
            }

            return RedirectToAction("index", "SysMenu");

        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            SysMenuInfo item = new SysMenuInfo();
            if (!string.IsNullOrEmpty(id))
                item = SysMenuBLL.GetInfoById(id);
            else
            {
                item.State = "1";
            }
            LoginInfo loginInfos = new LoginInfo();
            new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功, "更新菜单操作,操作成功,ID=" + id, "superadmin");
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(SysMenuInfo entity)
        {
            LoginInfo loginInfos = new LoginInfo();
            if (string.IsNullOrEmpty(entity.Id))
            {
                entity.Id = StringHelper.GetNewId();
                m_BLL.Insert(entity);
                new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功, "添加菜单操作,操作成功", "superadmin");
            }
            else
            {
                new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功, "更新菜单操作,操作成功,ID=" + entity.Id, "superadmin");
                m_BLL.Update(entity);
            }
            return RedirectToAction("Index", RouteData.Values);

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string deleteId = collection["query"].ToString();
            if (!string.IsNullOrEmpty(deleteId))
            {
                LoginInfo loginInfos = new LoginInfo();
                SysMenuBLL bll = new SysMenuBLL();
                bll.Delete(deleteId);
                new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "删除菜单操作,操作成功,ID=" + deleteId, "superadmin");
            }
            return Json("OK");
        }
        /// <summary>
        /// 获取树形列表的数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAllMetadata2(string id)
        {
            return null;
            //var rows = SysMenuBLL.GetInfoList().Select(s =>
            //            new
            //            {
            //                Id = s.Id
            //        ,
            //                Name = s.Name
            //        ,
            //                _parentId = s.ParentId
            //        ,
            //                isCheck = string.Join(",", s.SysOperation.Select(t => t.Id + "^" + t.Name))
            //        ,
            //                iconCls = s.Iconic

            //            }
            //            ).OrderBy(o => o.Id);

            //return Json(new treegrid() { rows = rows });

        }
        #endregion
    }
}
